import config
import os
from utils import *


def register():
	return Admin()


class Admin:
	def __init__(self):
		self.type = 'passive'
		self.help = \
'''管理员：
	用法：不告诉你
	支持管理员可使用的一系列高级指令。'''

	def run(self, gum, msg):
		if not msg['type'] in ('FriendMessage', 'GroupMessage') \
				or len(msg['messageChain']) <= 1 \
				or not msg['sender']['id'] in config.utils.admins \
				or msg['messageChain'][1]['type'] != 'Plain':
			return
		log('糖糖收到了管理员的消息哦！')
		for inst in config.bubbles.admin.insts:
			getattr(self, inst)(gum, msg, msg['messageChain'][1]['text'], msg['sender']['id'])

	def reload(self, gum, msg, text, target):
		if text == '*午睡':
			autoReply('糖糖想睡午觉了……zzz……', gum)
			gum.nap()

	def stop(self, gum, msg, text, target):
		if text == '*晚安':
			autoReply('糖糖可以休息了吗……？\n糖糖现在……已经很困了……', gum)
			gum.sleep()

	def say(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*悄悄话' and len(splitted) > 2 and splitted[1].isdigit():
			target = int(splitted[1])
			chain = MsgChain()
			for line in splitted[2:]:
				chain.addPlain(line + '\n')
			if len(msg['messageChain']) > 2:
				for section in msg['messageChain'][2:]:
					chain.addSection(section)
			sendFriends(chain, target)

	def groupSay(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*大声说' and len(splitted) > 2 and splitted[1].isdigit():
			target = int(splitted[1])
			chain = MsgChain()
			for line in splitted[2:]:
				chain.addPlain(line + '\n')
			if len(msg['messageChain']) > 2:
				for section in msg['messageChain'][2:]:
					chain.addSection(section)
			sendGroups(chain, target)

	def command(self, gum, msg, text, target):
		class Temp:
			pass
		tmp = Temp()
		splitted = text.split('\n')
		if splitted[0] == '*运行' and len(splitted) > 1:
			log('糖糖正在运行管理员的代码……')
			with trying():
				exec('\n'.join(splitted[1:]))

	def macaron(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*马卡龙' and len(splitted) > 1:
			log('糖糖正在吃马卡龙……')
			with open(config.miraigum.macaron.path, 'w') as f:
				for line in splitted[1:]:
						f.write(line + '\n')
			autoReply('吃完马卡龙就想睡觉了……zzz……', gum)
			gum.nap()

	def biscuit(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*小饼干' and len(splitted) > 1:
			log('糖糖正在吃小饼干……')
			with open(config.miraigum.biscuit.path, 'w') as f:
				for line in splitted[1:]:
					f.write(line + '\n')
			autoReply('糖糖喜欢吃小饼干', gum)

	def update(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*更新' and len(splitted) > 1:
			log('泡泡糖，机械飞升！')
			autoReply('泡泡糖，机械飞升！', gum)
			os.system(config.bubbles.admin.updateCommand)
			gum.nap()